package com.scs.application.modules.sys.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.entity.Office;
import com.scs.application.modules.sys.mapper.OfficeMapper;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.service.OfficeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  机构 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/office")
public class OfficeController extends CrudController<OfficeService, Office> {

    @Autowired
    private OfficeMapper officeMapper;

    /**
     * 获取数据列表
     */
    @Override
    public PageResult page(){
        QueryContext queryContext = QueryContextHolder.currentContext();
        IPage<HashMap<String,Object>> pageResult = officeMapper.getOfficeList(queryContext.getPage(), queryContext.getWrapper());
        if (pageResult.getTotal() > 0) {
            pageResult.getRecords().stream().forEach( item -> {
                if (StringUtils.isBlank(item.get("parentName") +"") && (StringUtils.isBlank(item.get("parentId") +"") || "0".equals(item.get("parentId") +""))) {
                    item.put("parentName", "全部机构");
                }
            });
        }

        return PageResult.ok("get Office list success", pageResult.getRecords(), pageResult.getTotal());
    }


    private void fillData(Office entity) {
        if (StringUtils.isBlank(entity.getParentName()) && (StringUtils.isBlank(entity.getParentId()) || "0".equals(entity.getParentId()))) {
            entity.setParentName("全部机构");
            return;
        }
        Office parent =  service.getById(entity.getParentId());
        if (parent == null) {
            return;
        }
        entity.setParentName(parent.getName());
    }


    /***
     * @param id
     * @Description:  通用查找，单个
     */
    @Override
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        Office entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillData(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /***
     * @Description:  通用删除，多个
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        Collection<Office> list =  service.listByIds(ids);
        if (list == null || ObjectUtil.length(list) != ObjectUtil.length(ids)) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        List<Office> childList = service.list(Wrappers.<Office>query().in("parent_id", ids));
        if (ObjectUtil.length(childList) > 0) {
            BusinessException.throwError("机构[{}]，存在下级节点[{}]，不允许删除",
                    list.stream().filter(tmp -> tmp.getId().equals(childList.get(0).getParentId())).findFirst().get().getName(),
                    childList.get(0).getName());
        }
        Boolean isOk = service.removeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        return RestResult.ok("数据删除成功");
    }

    /**
     * 添加/更新数据
     */
    @Override
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public RestResult saveItem(@RequestBody Office entity){
        boolean isOk = service.saveOrUpdateOffice(entity);
        if(!isOk){
            return RestResult.error("数据保存失败！");
        }
        fillData(entity);
        return RestResult.ok("数据保存成功", entity);
    }

}
